aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/send/invoice/[id]/+page.server.ts
blob: 3ef933d4fa3c6522eb23755d04023942612185d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import getRates from "$lib/rates";
import { auth, fd, get, post, types } from "$lib/utils";
import { error, redirect } from "@sveltejs/kit";

export async function load({ cookies, params: { id }, parent }) {
	const { user } = await parent();
	const aid = cookies.get("aid") || user.id;

	const invoice = await get(`/invoice/${id}`);

	if (invoice.amount && invoice.prompt && invoice.tip === null)
		redirect(307, `/invoice/${id}/tip`);

	if (invoice.memoPrompt && invoice.memo === null)
		redirect(307, `/invoice/${id}/memo`);

	if (user && invoice.aid === aid)
		error(500, { message: "Cannot send to self" });
	else if (user && ![types.lightning, types.bolt12].includes(invoice.type))
		redirect(
			307,
			`/send/${invoice.type === types.ecash ? "ecash" : "bitcoin"}/${
				invoice.hash
			}`,
		);

	if (!user) redirect(307, `/invoice/${id}`);

	const rates = await getRates();
	const rate = rates[user.currency];
	const invoiceRate = rates[invoice.currency];

	const { balance } = await get(`/account/${aid}`, auth(cookies));
	return { balance, invoice, user, rate, invoiceRate };
}

export const actions = {
	default: async ({ cookies, params: { id }, request }) => {
		let p;
		try {
			const body = await fd(request);
			body.hash = id;

			p = await post("/payments", body, auth(cookies));
		} catch (e) {
			const { message } = e as Error;
			console.log("payment failed", id, e);
			error(500, message);
		}

		redirect(307, `/sent/${p.id}`);
	},
};